<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserAddressRequest;
use App\Models\Address;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use const http\Client\Curl\AUTH_ANY;

class AddressController extends Controller
{
    /**
     * 获取所有的地址数据
     *
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function index()
    {
        $user=\Auth::user();
        return  UserAddress::where('user_id',$user->id)->orderBy('last_used_at','desc')->get();
    }

    public function create(Request $request) {
        if ($request->has('parent_id')) {
            $address=Cache::rememberForever('address_'.$request->input('parent_id'),function()use ($request) {
                return Address::where('parent_id',$request->input('parent_id'))->with('next')->get();
            });
        }else {
            $address= Cache::rememberForever('address_0',function()use ($request) {
                return Address::where('parent_id',0)->get();
            });

        }
        return $address;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return UserAddress|\Illuminate\Database\Eloquent\Model
     */
    public function store(UserAddressRequest $request)
    {
        $address=new UserAddress($request->all());
        $address->user_id=auth('api')->id();
        $address->last_used_at=Carbon::now();
        $address->save();
        return  $address;
    }

    /**
     * Display the specified resource.
     *
     * @param UserAddress $address
     * @return UserAddress|UserAddress[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function show(UserAddress $address)
    {
        return $address;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param UserAddressRequest $request
     * @param UserAddress $address
     * @return UserAddress
     */
    public function update(UserAddressRequest $request, UserAddress $address)
    {
        $this->authorize('update',$address);
        $address->update($request->all());
        return $address;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param UserAddress $address
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|Response|object
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function destroy(UserAddress $address)
    {
        $this->authorize('destroy',$address);
        $address->delete();
        return \response('',204);
    }
}
